/**
 *
 */

package it.bd.SetAllConnectionsOff.helper;

import android.content.ContentResolver;
import android.content.ContextWrapper;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;

/**
 * @author Lohmar
 */
public class PowerHelper extends APreferenceAware<Integer> {
    public static final String PREFS_KEY = "brightness";

    private static PowerHelper instance  = null;

    public static PowerHelper getInstance() {
        if (instance == null) {
            Log.e("", "NetworkHelper not initialized !");
        }
        return instance;
    }

    private ContextWrapper  context;
    private ContentResolver contentResolver;
    private Window          window;

    public PowerHelper(ContextWrapper context, ContentResolver contentResolver, Window window) {
        this.context = context;
        this.contentResolver = contentResolver;
        this.window = window;
        instance = this;
    }

    @Override
    ContextWrapper getContext() {
        return context;
    }

    @Override
    String getPrefKey() {
        return PREFS_KEY;
    }

    public int getScreenBrighteness() {
        int curBrightnessValue = -1;
        try {
            curBrightnessValue = Settings.System.getInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS);
        } catch (SettingNotFoundException e) {
            e.printStackTrace();
        }
        return curBrightnessValue;
    }

    public boolean isBrightnessAutomatic() {
        return Settings.System.getInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE, -1) == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
    }

    public void setBrightnessAutomatic(boolean brightnessAutomatic) {
        int iBrightnessAutomatic = brightnessAutomatic ? Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC
                : Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL;
        Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE, iBrightnessAutomatic);
    }

    public void setScreenBrighteness(int brightness) {
        WindowManager.LayoutParams lp = window.getAttributes();
        brightness = Math.max(brightness, 30);
        Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS, brightness);
        lp.screenBrightness = brightness / 255.0f;
        window.setAttributes(lp);
    }

}
